angular.module('starter.controllers', [])
.controller('orderTicketCtrl', function($scope, $q,meilvFac, timeString, $ionicActionSheet, $timeout, $stateParams, $location) {
  $scope.baseMonth = new Date().getMonth();
  $scope.tmpsMonth = $scope.baseMonth;
  $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);
  $scope.currentMonthInt = new Date($scope.currentMonth).setHours(0,0,0,0)/1000;//某月一号0:0:0
  $scope.order = {};
  $scope.order.num = 0;
  $scope.order.type = $stateParams.type;
  $scope.selected_price = 0;

  $scope.events = [];

  $scope.type = function(){
    switch($stateParams.type){
      case '1': return '成人票';
      case '2': return '儿童票';
      case '3': return '老人票';
      case '4': return '成人两日联票';
      case '5': return '儿童两日联票';
      case '6': return '老人两日联票';
      default: return;
    }
  };

  //获取迪士尼超旺季时间
  $scope.getDisneyHoliday = function(){
    var deferred = $q.defer();
    meilvFac.disney.disneyholidayget(function(data){
      $scope.disneyholiday = data.info;
      deferred.resolve();
    },function(data){
      alert(data.data.info);
    });
    return deferred.promise;
  };
  var disneyHolidayPromise = $scope.getDisneyHoliday();

  //获取节假日
  $scope.getHoliday = function(){
    var deferred = $q.defer();
    $scope.currentLastDay = new Date().setMonth($scope.tmpsMonth+1,1);
    $scope.currentLastDay = new Date($scope.currentLastDay).setHours(0,0,0,0)/1000-1;

    meilvFac.holiday.holidayget({
      date_start: $scope.currentMonthInt,
      date_end: $scope.currentLastDay
    },function(data){
      $scope.holidays = data.info;
      angular.forEach($scope.holidays,function(holiday){
        var holidaytmp = {};
        var start = timeString.toDateString(holiday.date_start);
        var end = timeString.toDateString(holiday.date_end+24*3600);
        holidaytmp.start = start;
        holidaytmp.end = end;
        holidaytmp.rendering = 'background';
        holidaytmp.backgroundColor = '#FAEED7';
        $scope.events.push(holidaytmp);
      });
      deferred.resolve();
    },function(data){
      alert(data.data.info);
    });
    return deferred.promise;
  };

  //获取各个季节价格
  $scope.getDisneyPrice = function(){
    var deferred = $q.defer();
    meilvFac.disney.disneypriceget(function(data){
      console.log(data)
      if(data.success){
        $scope.disneyprice = data.info;
        $scope.disneyprice.adult_common = parseInt($scope.disneyprice.adult_common);
        $scope.disneyprice.adult_hot = parseInt($scope.disneyprice.adult_hot);
        $scope.disneyprice.adult_superhot = parseInt($scope.disneyprice.adult_superhot);
        $scope.disneyprice.old_child_hot = parseInt($scope.disneyprice.old_child_hot);
        $scope.disneyprice.old_child_superhot = parseInt($scope.disneyprice.old_child_superhot);
        $scope.disneyprice.old_child_common = parseInt($scope.disneyprice.old_child_common);
      }else{
        $scope.disneyprice.adult_common=0;
        $scope.disneyprice.adult_hot=0;
        $scope.disneyprice.adult_superhot=0
        $scope.disneyprice.old_child_hot= 0;
        $scope.disneyprice.old_child_superhot= 0;
        $scope.disneyprice.old_child_common= 0;
      }
      deferred.resolve();
    },function(data){
      alert(data.data.info);
    });
    return deferred.promise;
  };
  var disneyPricePromise = $scope.getDisneyPrice();

  $scope.dateRecognize = function(time){
      var day = new Date(time*1000).getDay();
      var vholiday = false;
      angular.forEach($scope.holidays,function(holiday){
        if(time>=holiday.date_start&&time<=holiday.date_end){
          vholiday = true;
        }
      });

      if($stateParams.type=='1'||$stateParams.type=='4'){
          /*成人价格判断*/
        if(vholiday){ 
        result_price = $scope.disneyprice.adult_superhot;
        return result_price;
        }else
        if(time>=$scope.disneyholiday.date_start&&time<=$scope.disneyholiday.date_end&&(day==0||day==6)){//判断是否是旺季的双休
        result_price = $scope.disneyprice.adult_superhot;
        return result_price;
        }
        else if(time>=$scope.disneyholiday.date_start&&time<=$scope.disneyholiday.date_end){
        result_price = $scope.disneyprice.adult_hot;
        return result_price;
        }
        else if(day==0||day==6){
        result_price = $scope.disneyprice.adult_hot;
        return result_price;
        }
        else{
        result_price = $scope.disneyprice.adult_common;
        return result_price;
        }
      }
      else{
        /*老人和孩子的判断*/
        if(vholiday){ 
        result_price = $scope.disneyprice.old_child_superhot;
        return result_price;
        }
        else if(time>=$scope.disneyholiday.date_start&&time<=$scope.disneyholiday.date_end&&(day==0||day==6)){//判断是否是旺季的双休
          result_price = $scope.disneyprice.old_child_superhot;
          return result_price;  
        }
        else if(time>=$scope.disneyholiday.date_start&&time<=$scope.disneyholiday.date_end){
          result_price = $scope.disneyprice.old_child_hot;
          return result_price;
        }
        else if(day==0||day==6){
          result_price = $scope.disneyprice.old_child_hot;
          return result_price;
        }
        else{
          result_price = $scope.disneyprice.old_child_common;
          return result_price;
        }
      }
  };

  $scope.priceInit = function(){
    var deferred = $q.defer();
    var holidayPromise = $scope.getHoliday();
    holidayPromise.then(function(){
      $q.when($q.all([disneyHolidayPromise,disneyPricePromise])).then(function(){
        var priceEvents = [];//存放当前月price信息
        var year = new Date($scope.currentMonthInt*1000).getYear();
        var month = new Date($scope.currentMonthInt*1000).getMonth()+1;
        var d = new Date(year,month,0);
        var dateCount = d.getDate();//计算当月天数
        var i;
        var today = new Date().getDate();
        for(i=0;i<dateCount;i++){
          var price_e = {};
          price_e.start = timeString.toDateString($scope.currentMonthInt + i * 24 * 3600);
          price_e.end = timeString.toDateString($scope.currentMonthInt + (i+1) * 24 * 3600 - 1);
          price_e.title = '￥' + $scope.dateRecognize($scope.currentMonthInt + i * 24 * 3600);

          if((i+1)<=today&&$scope.tmpsMonth == $scope.baseMonth){
            price_e.textColor = '#ccc';
          }else{
            price_e.textColor = '#FF6328';
          }
          priceEvents.push(price_e);
        }
        $scope.events = $scope.events.concat(priceEvents);
        deferred.resolve();
      });
    });
    
    return deferred.promise;
  };

  $scope.initCal = function(){
    var pricePromise = $scope.priceInit();
    pricePromise.then(function(){
      $('#calendar').fullCalendar({
        // put your options and callbacks here
        lang: 'zh-cn',//显示语言
        header: false,
        defaultDate: $scope.currentMonth,
        columnFormat: 'dd',
        height: 386,
        selectable: true,
        editable: true,
        events: $scope.events,
        timezone: 'local',
        dragScroll: false,
        eventColor: "transparent",
        // eventTextColor: "#FF6328",
        eventBackgroundColor: 'transparent',
        dayClick: function(date, jsEvent, view) {
          var today = new Date().setHours(0,0,0,0)/1000;
          var selected_day = new Date(date).setHours(0,0,0,0)/1000;
          //选中日期的时间戳
          $scope.order.tour_time = timeString.toTimeNum(date.format());
          if($scope.order.tour_time >= today+24*3600){
            $(".fc-highlight").removeClass("fc-highlight");
            $(jsEvent.target).addClass("fc-highlight");
          }
          $scope.selected_price = $scope.dateRecognize(selected_day);
          $scope.selected_next_price = $scope.dateRecognize(selected_day+24*3600);
          console.log($scope.selected_price,$scope.selected_next_price);
          $scope.$apply();
          if(selected_day>=today){
            angular.forEach($scope.events, function(event){
              var date = timeString.toTimeNum(event.start);
              if(date >= today+24*3600 && date == selected_day){
                event.textColor = '#fff';
              }else if(date >= today+24*3600){
                event.textColor = '#FF6328';
              }
            });
          }
          $('#calendar').fullCalendar('removeEvents');
          $('#calendar').fullCalendar('addEventSource', $scope.events);
        }
      });
      $('.fc-day-grid-container').css("overflow-y","hidden");
      $scope.current_day = $('#calendar').fullCalendar('getView').title;
    });
  };
  $scope.initCal();

  $scope.prev = function(){
    if($scope.tmpsMonth > $scope.baseMonth){
      $scope.tmpsMonth --;
      $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);
      $scope.currentMonthInt = new Date($scope.currentMonth).setHours(0,0,0,0)/1000;//某月一号0:0:0
      $scope.events = [];
      $scope.order.tour_time = null;
      $scope.selected_price = 0;
      $scope.selected_next_price = 0;
      $scope.total_price = 0;
      var pricePromise = $scope.priceInit();
      pricePromise.then(function(){
        $('#calendar').fullCalendar('prev');
        $('#calendar').fullCalendar('removeEvents');
        $('#calendar').fullCalendar('addEventSource', $scope.events);
        $scope.current_day = $('#calendar').fullCalendar('getView').title;
      });
    }
  };

  $scope.next = function(){
    if($scope.tmpsMonth < $scope.baseMonth + 6){
      $scope.tmpsMonth ++;
      $scope.currentMonth = new Date().setMonth($scope.tmpsMonth,1);
      $scope.currentMonthInt = new Date($scope.currentMonth).setHours(0,0,0,0)/1000;//某月一号0:0:0
      $scope.events = [];
      $scope.order.tour_time = null;
      $scope.selected_price = 0;
      $scope.selected_next_price = 0;
      $scope.total_price = 0;
      var pricePromise = $scope.priceInit();
      pricePromise.then(function(){
        $('#calendar').fullCalendar('next');
        $('#calendar').fullCalendar('removeEvents');
        $('#calendar').fullCalendar('addEventSource', $scope.events);
        $scope.current_day = $('#calendar').fullCalendar('getView').title;
      });
    }
  };

  //监视日历左箭头，等于当前月份时，变为灰色
  $scope.$watch('tmpsMonth',function(){
    if($scope.tmpsMonth == $scope.baseMonth)
      $scope.downLimit = true;
    else
      $scope.downLimit = false;
  });

  //监视日历右箭头，等于当前月份+6时，变为灰色
  $scope.$watch('tmpsMonth',function(){
    if($scope.tmpsMonth == $scope.baseMonth + 6)
      $scope.upLimit = true;
    else
      $scope.upLimit = false;
  });

  // Triggered on a button click, or some other target
  $scope.minus = function(){
    if($scope.order.num>0) 
      $scope.order.num--;
  }; 

  $scope.plus = function(){
    $scope.order.num++;
  };

  //监视购买数量
  $scope.$watch('order.num',function(){
    if($scope.order.num>5){
      $scope.order.num = 5;
    }
  });

  $scope.nextstep = function(){
    if(!$scope.order.tour_time){
      alert('请选择出行日期！');
      return;
    }
    if(!$scope.order.num){
      alert('请至少购买1张票！');
      return;
    }
    $location.url('ticketnext/'+ $scope.order.type+ '/' + $scope.order.tour_time + '/' + $scope.order.num + '/' + $scope.total_price);
  };

  
  $scope.totalPrice = function(){
    console.log($scope.total_price);
    if($stateParams.type=='1'||$stateParams.type=='2'||$stateParams.type=='3'){
      $scope.total_price = $scope.selected_price * $scope.order.num; 
    }else{
      $scope.total_price = ($scope.selected_price + $scope.selected_next_price) * $scope.order.num * 0.95; 
    }
    if($scope.total_price)
      return $scope.total_price;
    else
      return 0;
    
  };

})